package com.yugao.fintech.antelope.pay.payment;

import com.alibaba.fastjson2.JSON;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.exception.ValidationException;
import com.yugao.fintech.framework.core.response.Resp;
import com.yugao.fintech.framework.web.handler.GlobalExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理,throw new BusinessException(ResultEnum.FAILURE);要在控制层中使用，如果在服务层使用，不会
 * 走BusinessException方法处理，只会走Exception方法进行处理
 * 以下来自stackoverflow
 */
@ControllerAdvice
@RestController
public class PayExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @PostConstruct
    public void init() {
        log.info("init {}", this.getClass().getName());
    }

    /**
     * 微信 - 发送HTTP请求失败时抛出。例如构建请求参数失败、发送请求失败、I/O错误等。包含请求信息
     */
    @ExceptionHandler(HttpException.class)
    public Object wxHttpException(HttpException e, HttpServletRequest request) {
        log.error("exception: {}, url: {}", e.getMessage(), request.getRequestURI());
        log.debug(e.getMessage(), e);
        return Resp.fail(e.getMessage()).wrapOfServlet();
    }

    /**
     * 微信 - 验证签名失败时抛出
     */
    @ExceptionHandler(ValidationException.class)
    public Object wxValidationException(ValidationException e, HttpServletRequest request) {
        log.error("exception: {}, url: {}", e.getMessage(), request.getRequestURI());
        log.debug(e.getMessage(), e);
        return Resp.fail(e.getMessage()).wrapOfServlet();
    }

    /**
     * 微信 - 发送HTTP请求成功，服务返回异常。例如返回状态码小于200或大于等于300。
     */
    @ExceptionHandler(ServiceException.class)
    public Object wxServiceException(ServiceException e, HttpServletRequest request) {
        log.error("exception: {}, url: {}", e.getMessage(), request.getRequestURI());
        log.debug(e.getMessage(), e);
        return Resp.fail(JSON.parseObject(e.getResponseBody(), Exception.class).getMessage()).wrapOfServlet();
    }

    /**
     * 微信 - 服务返回成功，content-type不为application/json、解析返回体失败。
     */
    @ExceptionHandler(MalformedMessageException.class)
    public Object wxMalformedMessageException(MalformedMessageException e, HttpServletRequest request) {
        log.error("exception: {}, url: {}", e.getMessage(), request.getRequestURI());
        log.debug(e.getMessage(), e);
        return Resp.fail(e.getMessage()).wrapOfServlet();
    }
}
